package com.caoJun.jdbcTemplate;

import com.caoJun.pojo.Account;
import org.junit.Test;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

/**
 * @Description: SSM_homework
 * @Author 83-start
 * @Time 2021/4/21 21:03
 */
public class AccountDaoImpl implements AccountDao {
    private JdbcTemplate jdbcTemplate;

    public AccountDaoImpl(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public AccountDaoImpl() {
    }

    /**
     * 通过用户的 id 来查询用户的余额
     *
     * @param id
     * @return
     */
    @Override
    public double selectBalanceById(int id) {
        String sql = "SELECT balance FROM account WHERE id = ?";
        // 创建一个新的BeanPropertyRowMapper 对象
        BeanPropertyRowMapper<Account> rowMapper = new BeanPropertyRowMapper<Account>(Account.class);
        // 将 id 绑定到SQL 语句中
        Account account = this.jdbcTemplate.queryForObject(sql, rowMapper, id);
        // 获取balance 的余额
        double balance = account.getBalance();
        return balance;
    }

    /**
     * 更新用户的账户余额
     *
     * @param id
     * @param balance
     */
    @Override
    public void updateBalance(int id, double balance) {
        String sql = "UPDATE account SET balance = ? WHERE id= ?";
        // 定义数组来存储SQL 语句中的参数
        Object[] objects = new Object[]{balance, id};
        // 执行更新操作
        int update = this.jdbcTemplate.update(sql, objects);
        System.out.println(update > 0 ? "操作成功" : "操作失败");
    }

    /**
     * 增加用户
     *
     * @param account
     */
    @Override
    public void addAccount(Account account) {
        // 定义sql语句
        String sql = "INSERT INTO account(username,balance) VALUES (?,?)";

        // 定义数组
        Object[] objects = {
                account.getUsername(),
                account.getBalance()
        };
        // 执行语句
        int update = this.jdbcTemplate.update(sql, objects);
        System.out.println(update > 0 ? "增加用户成功" : "增加用户失败");
    }

    /**
     * 通过id 来删除用户
     *
     * @param id
     */
    @Override
    public void deleteAccountById(int id) {
        // 定义sql 语句
        String sql = "DELETE FROM account WHERE id = ?";
        // 执行删除语句
        int delete = this.jdbcTemplate.update(sql, id);
        System.out.println(delete > 0 ? "删除成功" : "删除失败");

    }

}
